package cn.leedsoft.luma.web_service;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * Created by leeds on 2016/11/8 13:39.
 */
public class OssClientHelper {
    private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private static String accessKeyId = "VPl9GcZpFkIZyEfK";
    private static String accessKeySecret = "iFbOtHP1242SPum3DnbITPFplmfVT7";
    private static String fileDomain = "http://file.sinodental.medtrib.cn/";
    public static final String BUCKET_NAME = "sinodental-file";
    public static final OSSClient CLIENT = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    public String putMultipartFile(MultipartFile multipartFile, String path) throws IOException {
        //meta
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType(multipartFile.getContentType());
        meta.setContentLength(multipartFile.getSize());
        meta.setCacheControl("max-age=86400000");
        String originName = multipartFile.getOriginalFilename();
        meta.addUserMetadata("originalFilename", originName);
        String encodedName = URLEncoder.encode(originName, "utf-8").replaceAll("\\+", "%20");
        String howDisplay = "attachment";
        if (StringUtils.startsWithAny(multipartFile.getContentType(), "image/", "application/pdf")) {
            howDisplay = "inline";
        }
        meta.setContentDisposition(String.format("%1$s;filename=%2$s", howDisplay, encodedName));

        //path
        String fileKey = path + File.pathSeparator + UUID.randomUUID().toString().replaceAll("-", "");
//        client.getObject()

        CLIENT.putObject(BUCKET_NAME, fileKey, multipartFile.getInputStream(), meta);
        //url
        String url = fileDomain + path;
        return url;
    }
}
